from flask import Flask, render_template, request, redirect, url_for, session, flash
from model import UserModel
import os
from dotenv import load_dotenv
from index import index_bp
from predict import predict_bp
from search import search_bp
from train import train_bp
import matplotlib
from screen import screen_bp
from pyspark.sql import SparkSession

spark = SparkSession.builder \
    .appName("AbaloneAgePrediction") \
    .config("spark.executorEnv.PYSPARK_PYTHON", "python") \
    .config("spark.yarn.appMasterEnv.PYSPARK_PYTHON", "python") \
    .getOrCreate()
matplotlib.use('Agg')  # 使用非GUI后端

load_dotenv()


app = Flask(__name__)
app.secret_key = os.getenv('SECRET_KEY', 'your_secret_key_here')
app.config['MODEL_DIR'] = 'models'

# 配置中文字体
try:
    from matplotlib.font_manager import FontProperties

    font_path = 'C:/Windows/Fonts/simhei.ttf'  # Windows系统字体路径
    zh_font = FontProperties(fname=font_path)
    matplotlib.rcParams['font.sans-serif'] = [zh_font.get_name()]
    matplotlib.rcParams['axes.unicode_minus'] = False
except:
    matplotlib.rcParams['font.sans-serif'] = ['Arial Unicode MS', 'Microsoft YaHei', 'SimHei']

# 数据库配置
db_config = {
    'host': os.getenv('DB_HOST', 'localhost'),
    'user': os.getenv('DB_USER', 'root'),
    'password': os.getenv('DB_PASSWORD', '123456'),
    'database': os.getenv('DB_NAME', 'Ab_data')
}

# 注册蓝图（统一使用/前缀）
app.register_blueprint(index_bp, url_prefix='')
app.register_blueprint(predict_bp)
app.register_blueprint(search_bp)
app.register_blueprint(train_bp, url_prefix='')
app.register_blueprint(screen_bp)
# 用户模型实例化
user_model = UserModel(db_config)

# 注册蓝图

@app.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        user = user_model.authenticate(username, password)
        if user:
            session['user_id'] = user['id']
            session['username'] = user['username']
            flash('登录成功!', 'success')
            return redirect(url_for('index.index'))
        else:
            flash('用户名或密码错误', 'danger')

    return render_template('login.html')


@app.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        confirm_password = request.form['confirm_password']

        if password != confirm_password:
            flash('两次输入的密码不一致', 'danger')
            return render_template('register.html')

        try:
            user_model.create_user(username, password)
            flash('注册成功! 请登录', 'success')
            return redirect(url_for('login'))
        except Exception as e:
            flash(str(e), 'danger')

    return render_template('register.html')


@app.route('/logout')
def logout():
    session.clear()
    flash('您已成功退出登录', 'info')
    return redirect(url_for('login'))


if __name__ == '__main__':
    # 确保模型目录存在
    os.makedirs(app.config['MODEL_DIR'], exist_ok=True)
    app.run(debug=True)